package concordia.comp6231.server;

import concordia.comp6231.common.ApplicationConfig;
import concordia.comp6231.rfmulticast.ListernerHandler;
import concordia.comp6231.rfmulticast.Message;
import concordia.comp6231.rfmulticast.RFIFOMulticast;
import static concordia.comp6231.common.ApplicationConfig.*;

public class ReplicaListener implements ListernerHandler {

	@Override
	public Message handleResult(Message msg) {
		String msgType = msg.get("msg_type");
		Message resultMsg = new Message();
		resultMsg.put("msg_type", "replica_broadcast_request");
		if ("replica_broadcast_request".equals(msgType)) {
			String actionName = msg.get("action_name");
			if ("check".equals(actionName)) {
				String showID = msg.get("showID");
				int checkResult = ReplicaMember.currentInstance().getBoxOfficeImpl().check(showID);
				resultMsg.put("check_result", new Integer(checkResult).toString());
			} else if ("reserve".equals(actionName)) {
				String customerID = msg.get("customerID");
				String showID = msg.get("showID");
				int numberOfTickets = msg.getAsInt("numberOfTickets");
				ReplicaMember.currentInstance().getBoxOfficeImpl().reserve(customerID, showID, numberOfTickets);
			} else if ("cancel".equals(actionName)) {
				String customerID = msg.get("customerID");
				String showID = msg.get("showID");
				int numberOfTickets = msg.getAsInt("numberOfTickets");
				ReplicaMember.currentInstance().getBoxOfficeImpl().cancel(customerID, showID, numberOfTickets);
			} else if ("exchange".equals(actionName)) {
				String customerID = msg.get("customerID");
				String reservedShowID = msg.get("reservedShowID");
				int reservedTickets = msg.getAsInt("reservedTickets");
				String desiredShowID = msg.get("desiredShowID");
				int desiredTickets = msg.getAsInt("desiredTickets");
				ReplicaMember.currentInstance().getBoxOfficeImpl().exchange(customerID, reservedShowID, reservedTickets, desiredShowID, desiredTickets);
			}			
		}
		return resultMsg;
	}
	
	public void startListener() {
		RFIFOMulticast rfm = new RFIFOMulticast();
		rfm.listen(ApplicationConfig.getAsInt(REPLICA_SERVER_PORT), this);
	}

}
